import { ref, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import { getMarkData as FeatchMarkList, addMark, updateMarkStatus } from '@/api/userManage/userManage';
import type { MarkItem } from '@/api/userManage/userManage.d';
import type { CallBackData } from '@/components/dialog/type.d';

export default function useMark() {
    const addMarkVisibile = ref(false);
    const addMarkForm = ref({
        name: '',
        remark: ''
    })
    const formRef = ref();

    const markList = ref<MarkItem[]>([]);

    // 新增单元点击
    const handeleAddMarkClick = () => {
        addMarkVisibile.value = true;
    }

    // 获取标注单位list
    const getMarkData = async() => {
        const params = {};
        const res = await FeatchMarkList(params);
        res && (markList.value = res.data);
    }

    // 新增单元弹窗
    const handleMarkVisible = async (data: CallBackData) => {
        if (data.status === 'save') {
            const res = await formRef.value.validate();
            data.done(true);
            if (res === undefined) {
                const res: any = await addMark({
                    ...addMarkForm.value
                })
                if (res.code === 200 || res.code === 0) {
                    Message.success('新增成功');
                    formRef.value.resetFields();
                    addMarkVisibile.value = data.flag;
                    getMarkData();
                } else {
                    if (res.msg.includes("名称")) {
                        formRef.value.setFields({
                            name: {
                                status: "error",
                                message: "单位名称重复，请修改后添加！"
                            }
                        })
                    }
                }
            }
        } else if (data.status === 'clear') {
            formRef.value.resetFields();
            addMarkVisibile.value = data.flag;
        }
    };

    // 改变单位列表状态
    const handleMarkStatus = async (item: MarkItem, value: string | number | boolean, ev: Event) => {
        ev.stopPropagation();
        if (typeof value === 'number') {
            item.status = value;
            const params = {
                id: item.id,
                status: item.status
            }
            const res = await updateMarkStatus(params);
            // @ts-ignore
            if (res?.code === 200) {
                Message.success('修改成功');
                getMarkData();
            }
        }
    };

    return {
        addMarkVisibile,
        addMarkForm,
        formRef,
        markList,
        handeleAddMarkClick,
        getMarkData,
        handleMarkVisible,
        handleMarkStatus
    }
}